<template>
	<div @click="onWeiXinLogin">
		<m-svg-icon class="w-4 h-4 cursor-pointer" name="wexin"></m-svg-icon>
		<div id="login_container" v-show="false"></div>
	</div>
</template>

<script setup>
import { ref } from 'vue'
import {
	getWXLoginData,
	getWXAccessToken,
	getWXLoginUserInfo,
} from '@/api/sys/index.js'
import brodacast from './brodacast'
import { oauthLogin } from './oauth.js'

// 微信登录成功后数据解析
if (window.location.search) {
	const code = /code=((.*))&state/.exec(window.location.search)[1]

	if (code) {
		brodacast.send({ code })
	}
	window.close()
}

const onWeiXinLogin = async () => {
	const { appId, appSecret, redirectUri, scope, state } = await getWXLoginData()

	window.open(
		`https://open.weixin.qq.com/connect/qrconnect?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`,
		'',
		'height=525,width=585, toolbar=no, menubar=no, scrollbars=no, status=no,location=yes, resizable=yes'
	)

	brodacast.wait().then(async ({ code }) => {
		brodacast.clear()

		// 触发获取token接口
		const { access_token, openid } = await getWXAccessToken(
			appId,
			appSecret,
			code
		)

		// 获取用户信息
		const { nickname, headimgUrl } = await getWXLoginUserInfo(
			access_token,
			openid
		)

		// 执行登录操作
		// 执行登录操作
		oauthLogin('WX', {
			openid,
			nickname,
			headimgUrl,
		})
	})
}
</script>

<style scoped lang="scss"></style>
